import 'package:http/http.dart' as http;
import 'package:webfeed/webfeed.dart';
import 'package:intl/intl.dart';
import 'dart:io';

handleDate(DateTime datetime) {
  Handler(datetime).handle();
}

class Handler {
  DateTime dt;

  Handler(this.dt);

  void handle() async {
    var response = await http.get("http://www.kikt.top/index.xml");
    var body = response.body;

    var atomFeed = new RssFeed.parse(body);
    var df = DateFormat("EEE, d MMM yyyy hh:mm:ss");
    var outDf = DateFormat("yyyy-MM-dd hh:mm:ss");
    for (var it in atomFeed.items.reversed) {
      if (!isAfter(it)) {
        continue;
      }
      var dt = df.parse(it.pubDate);

      print("${outDf.format(dt)}  //// ${it.pubDate}");
      var currentPath = convertLinkToFile(it.link);

      print(it.title);
      print(it.link);
      print("file://$currentPath");

      print("\n\n");
    }

    // var doc = xml.parse(body);
    // handleDoc(doc);
  }

  bool isAfter(RssItem item) {
    var dateFormat = DateFormat("EEE, d MMM yyyy hh:mm:ss");
    var dt = dateFormat.parse(item.pubDate);
    return dt.isAfter(this.dt);
  }

  String convertLinkToFile(String link) {
    var uri = Uri.parse(link);

    var path = Uri.decodeFull(uri.path);
    if (path.endsWith("/")) {
      path = path.substring(0, path.length - 1);
    }

    print(uri.path);

    var dir = Directory.current;

    return dir.parent.absolute.path + "/content" + path + ".md";
  }
}
